package com.inspur.edp.formserver.vmmanager.lowcode;


import com.inspur.edp.formserver.viewmodel.extendinfo.api.GspVoExtendInfoService;
import com.inspur.edp.formserver.viewmodel.extendinfo.entity.GspVoExtendInfo;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataPackage;
import com.inspur.edp.lcm.metadata.spi.event.MdPkgChangedArgs;
import com.inspur.edp.lcm.metadata.spi.event.MdPkgChangedEventListener;
import com.inspur.edp.metadata.rtcustomization.api.CustomizationService;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class MdPkgDeployListener implements MdPkgChangedEventListener {

    CustomizationService metadataService;

    public MdPkgDeployListener() {
        this.metadataService = SpringBeanUtils.getBean(CustomizationService.class);
    }

    @Override
    public void fireMdPkgAddedEvent(MdPkgChangedArgs mdPkgChangedArgs) {
    }

    @Override
    public void fireMdPkgChangedEvent(MdPkgChangedArgs mdPkgChangedArgs) {
        if (metadataService == null) {
            this.metadataService = SpringBeanUtils.getBean(CustomizationService.class);
        }
        MetadataPackage metadataPackage = mdPkgChangedArgs.getMetadataPackage();
        clearVoCache(metadataPackage, metadataService);
    }

    public void clearVoCache(MetadataPackage metadataPackage, CustomizationService metadataService) {

        List<GspMetadata> packageMetadataList = metadataPackage.getMetadataList();
        if (packageMetadataList == null || packageMetadataList.isEmpty()) {
            return;
        }
        List<GspMetadata> metadatas = packageMetadataList.stream()
                .filter(item -> item.getHeader().getType().equals("GSPBusinessEntity"))
                .collect(Collectors.toList());
        if (metadatas.isEmpty()) {
            return;
        }
        ArrayList<String> metadataLists = new ArrayList<>();
        GspVoExtendInfoService service = SpringBeanUtils.getBean(GspVoExtendInfoService.class);
        for (GspMetadata metadata : metadatas) {
            List<GspVoExtendInfo> voExtendInfos = service.getVoId(metadata.getHeader().getId());
            if (voExtendInfos == null || voExtendInfos.size() == 0) {
                continue;
            }
            voExtendInfos.forEach(info -> metadataLists.add(info.getId()));
        }

        metadataService.removeCacheByMetadataIds(metadataLists);

    }

}
